<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="组织名称" prop="orgId">
          <ft-org-select v-model="listQuery.param.orgId" :placeholder="'组织名称'" :multiple="false" :default-expand-level="2" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="listQuery.param.username" placeholder="用户名" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="listQuery.param.mobile" placeholder="手机号" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="账户状态" prop="locked">
          <el-select v-model="listQuery.param.locked" placeholder="账户状态" style="width: 120px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in lockedOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 120px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="用户ID" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="90px" align="left">
        <template v-slot="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" min-width="120px" align="left">
        <template v-slot="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" min-width="50px" align="left">
        <template v-slot="{row}">
          <span v-if="row.gender === 'M'">男</span>
          <span v-else-if="row.gender === 'F'">女</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" min-width="50px" align="left">
        <template v-slot="{row}">
          <span>{{ row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生日" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.birthday | parseTime('{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" min-width="110px" align="left">
        <template v-slot="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="头像" min-width="80px" align="left">-->
      <!--        <template v-slot="{row}">-->
      <!--          <el-avatar size="medium" :src="row.avatar" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="所属组织" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.orgName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账户状态" min-width="70px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.locked === 'Y'" type="info">锁定</el-tag>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.edit" command="edit"><i class="el-icon-edit"> 编辑</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.pwd" command="pwd"><i class="el-icon-s-claim"> 重置密码</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 编辑页面 -->
    <el-drawer
      :visible.sync="visible"
      direction="rtl"
      size="40%"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :show-close="false"
    >
      <template v-slot:title>
        <div class="drawer-header">
          <span>{{ title[state] }}</span>
          <div>
            <el-button icon="el-icon-close" @click="handleClose">
              取消
            </el-button>
            <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
              <span v-if="!submitting">确认</span>
              <span v-else>提 交 中...</span>
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-input v-model="formData.userId" type="hidden" />
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" :readonly="state !== 'create'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="formData.userId" readonly placeholder="系统自动生成" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :disabled="state==='detail'"
              >
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" :disabled="state==='detail'" class="filter-item" style="width: 100%;" placeholder="请选择" clearable>
                <el-option key="M" label="男" value="M" />
                <el-option key="F" label="女" value="F" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="formData.age" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="formData.birthday" :readonly="state==='detail'" style="width: 100%;" type="date" format="yyyy-MM-dd" placeholder="请选择" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属组织" prop="orgId">
              <ft-org-select v-model="formData.orgId" :default-expand-level="2" :disabled="state==='detail'" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="用户岗位" prop="postId">
              <ft-post-select v-model="postIdSelects" :disabled="state==='detail'" multiple style="width: 100%;" placeholder="请选择" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="用户角色" prop="roleId">
              <ft-role-select v-model="roleIdSelects" :disabled="state==='detail'" multiple style="width: 100%;" placeholder="请选择" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="账户状态" prop="locked">
              <el-radio v-model="formData.locked" :disabled="state==='detail'" label="Y">锁定</el-radio>
              <el-radio v-model="formData.locked" :disabled="state==='detail'" label="N">正常</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-select v-model="formData.status" :disabled="state==='detail'" class="filter-item" style="width: 100%;" placeholder="请选择" clearable>
                <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" :readonly="state==='detail'" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>

    <!--详情页面-->
    <user-info-detail ref="userInfoDetail" :detail="detail" />
  </div>
</template>

<script>
import { handlePageList, handleDetail, handleSave, handleDelete, handlePwd } from '@/views/sys/userInfo/api'
import permission from '@/directive/permission/index' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import UserInfoDetail from '@/views/sys/userInfo/detail.vue'
import FtOrgSelect from '@/views/components/FtOrgSelect/index.vue'
import FtPostSelect from '@/views/components/FtPostSelect/index.vue'
import FtRoleSelect from '@/views/components/FtRoleSelect/index.vue'

export default {
  name: 'UserInfo',
  components: { Pagination, FtRoleSelect, FtPostSelect, FtOrgSelect, UserInfoDetail },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          username: undefined,
          mobile: undefined,
          orgId: undefined,
          locked: undefined,
          status: undefined
        }
      },
      // 状态字典
      lockedOptions: [{ code: 'Y', text: '锁定' }, { code: 'N', text: '正常' }],
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        add: ['sys:user:add'],
        edit: ['sys:user:edit'],
        pwd: ['sys:user:password'],
        del: ['sys:user:del']
      },
      submitting: false,
      // 表单校验规则
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'change' },
          { required: true, validator: this.handleCheckUsername, trigger: 'blur' }
        ],
        name: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        age: [{ required: true, message: '年龄不能为空', trigger: 'change' }, { type: 'number', message: '年龄必须为数字值' }],
        birthday: [{ required: true, message: '生日不能为空', trigger: 'change' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'change' }],
        orgId: [{ required: true, message: '所属不能为空', trigger: 'change' }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'change' }]
      },
      postIdSelects: [],
      roleIdSelects: [],
      // 详情data
      detail: {
        visible: false,
        data: {}
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 列表table数据在页面渲染完成后加载
    this.handleInit()
    // 初始化表单数据
    this.handleRestFormData()
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      handlePageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilterQuery()
    },
    // 检查用户是否重复
    handleCheckUsername(rule, value, callback) {
      if (this.state !== 'create') callback()
      if (!value) return callback()
      handleDetail({ username: value }).then(res => {
        if (res.data) {
          callback(new Error('用户名已存在'))
        } else {
          callback()
        }
      })
    },
    // 重置表单
    handleRestFormData() {
      this.formData = {
        id: undefined,
        userId: undefined,
        username: undefined,
        name: undefined,
        gender: undefined,
        age: undefined,
        birthday: undefined,
        email: undefined,
        mobile: undefined,
        orgId: undefined,
        roleId: undefined,
        postId: undefined,
        locked: 'N',
        status: 'Y',
        remark: ''
      }
      this.postIdSelects = []
      this.roleIdSelects = []
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 编辑
      if (item === 'edit') {
        this.handleUpdate(row, index)
      }
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
      // 重置密码
      if (item === 'pwd') {
        this.handlePwd(row, index)
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate(row) {
      this.state = 'update'
      this.visible = true
      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      //  这里要处理一下，要将string类型转为date
      this.formData.birthday = new Date(this.formData.birthday)

      if (this.formData.roleId) {
        this.roleIdSelects = this.formData.roleId.split(',')
      }
      if (this.formData.postId) {
        this.postIdSelects = this.formData.postId.split(',')
      }
      if (!this.formData.avatar) {
        // 使用 require 引入图片，会将图片路径转换为最终的 URL
        this.formData.avatar = require('./pic/avatar-1.jpg')
      }

      // 清理没有用的属性，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail(row) {
      // this.detail.visible = true
      // this.detail.data = Object.assign({}, row)
      // this.$nextTick(() => {
      //   this.$refs['userInfoDetail'].init()
      // })

      this.state = 'detail'
      this.visible = true
      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      //  这里要处理一下，要将string类型转为date
      this.formData.birthday = new Date(this.formData.birthday)
      if (this.formData.roleId) {
        this.roleIdSelects = this.formData.roleId.split(',')
      }
      if (this.formData.postId) {
        this.postIdSelects = this.formData.postId.split(',')
      }

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    handleDelete(row, index) {
      if (row.userId === '10000') {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '超级管理员用户不允许修改！',
          duration: 4000
        })
        return
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ userId: row.userId }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 重置密码
    handlePwd(row, index) {
      this.$prompt('请输入新密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{6,}$/,
        inputErrorMessage: '输入的内容长度不能少于 6 个字符'
      }).then(({ value }) => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handlePwd({ userId: row.userId, password: value }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.formData.birthday = parseTime(new Date(this.formData.birthday), '{y}-{m}-{d}')
          this.formData.roleId = this.roleIdSelects.join(',')
          this.formData.postId = this.postIdSelects.join(',')
          if (!this.formData.avatar) {
            this.formData.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
          }
          this.submitting = true
          handleSave(this.formData).then((res) => {
            this.submitting = false
            this.handleFilterQuery()
            this.handleClose()
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 图片上传前检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg/png'
      const isPNG = file.type === 'image/png'
      const isLt4M = file.size / 1024 / 1024 < 4

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!')
      }
      if (!isLt4M) {
        this.$message.error('上传头像图片大小不能超过 4MB!')
      }
      return (isJPG || isPNG) && isLt4M
    },
    // 图片上传后操作
    handleAvatarSuccess(res, file) {
      // this.avatar = URL.createObjectURL(file.raw)
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 字段默认 id label 用于规范化数据源
    handleTreeSelectNormalizer(node) {
      if (!node.children || !node.children.length) {
        delete node.children
      }
      return node
    },
    // 关闭弹出层
    handleClose() {
      this.$refs['dataForm'].resetFields()
      this.handleRestFormData()
      this.visible = false
    }
  }
}
</script>

<style>
.vue-treeselect__control{
  height: 32px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  line-height: 110px;
  text-align: center;
}
.avatar {
  width: 110px;
  height: 110px;
  display: block;
}

.el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio.is-disabled .el-radio__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled.is-checked {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__label {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-textarea.is-disabled .el-textarea__inner {
  background-color: #ffffff !important;
}
.vue-treeselect--disabled .vue-treeselect__control {
  background-color: #ffffff !important;
}
</style>
